package com.aqiang.day0528_shop.user.view.activity

import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.aqiang.day0528_shop.R
import com.aqiang.day0528_shop.ShopApplication
import com.aqiang.day0528_shop.user.contract.UserContract
import com.aqiang.day0528_shop.user.entity.DaoMaster
import com.aqiang.day0528_shop.user.entity.UserBean
import com.aqiang.day0528_shop.user.entity.UserBeanDao
import com.aqiang.day0528_shop.user.entity.UserEntity
import com.aqiang.day0528_shop.user.presenter.RegisterPresenter
import com.aqiang.lib_core.mvp.BaseActivity
import com.zy.shopproject2.usercenter.entity.BaseResponseEntity
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*
import java.util.regex.Pattern
import kotlin.concurrent.timerTask

class RegisterActivity : BaseActivity<UserContract.RegisterPresenter>(),UserContract.RegisterView {
    private var time:Int = 60
    private var auth:Int = 0
    override fun bindLatout(): Int {
        return R.layout.activity_register
    }

    override fun createPresenter() {
        mPresenter = RegisterPresenter(this)
    }

    override fun initView(savedInstanceState: Bundle?) {

    }

    override fun initData() {

    }

    override fun initEvent() {
        tv_act_register_deal.setOnClickListener {
            startActivity<DealActivity>()
        }
        bt_act_register_auth.setOnClickListener {
            val timer = Timer()
            bt_act_register_auth.isEnabled = false
            timer.schedule(timerTask {
                runOnUiThread {
                    bt_act_register_auth.text = "重新发送${time}"
                }
                time--
                if(time <= 0){
                    timer.cancel()
                    runOnUiThread {
                        bt_act_register_auth.text = "重新发送"
                        bt_act_register_auth.isEnabled = true
                    }
                }
            },0,1000)
            doAsynTask {
                mPresenter!!.auth()
            }
        }
        bt_act_register.setOnClickListener { v ->
            doAsynTask {
                var userReg:String = "^[1]\\d{10}$"
                if (!Pattern.matches(userReg,getUser()) && getUser().isEmpty()){
                    launch {
                        withContext(Dispatchers.Main){
                            toast("不能为空或者手机格式不对")
                        }
                    }
                    return@doAsynTask
                }
                if(getAuth() != auth.toString()){
                    launch {
                        withContext(Dispatchers.Main){
                            toast("验证码不对")
                        }
                    }
                    return@doAsynTask
                }
                if(!cb_act_register.isChecked){
                    launch {
                        withContext(Dispatchers.Main){
                            toast("请同意协议")
                        }
                    }
                    return@doAsynTask
                }
                if(getPwd() != et_act_register_repwd.text.toString()){
                    launch {
                        withContext(Dispatchers.Main){
                            toast("两次密码不同")
                        }
                    }
                    return@doAsynTask
                }
                mPresenter!!.register()
            }
        }
    }

    override fun getUser(): String {
        return et_act_register_user.text.toString()
    }

    override fun getPwd(): String {
        return et_act_register_pwd.text.toString()
    }

    override fun success(d: Deferred<BaseResponseEntity>) {
        doUiThread(d,{
            if(it.code == 200){
                toast("注册成功,可以去登陆")
                //保存
                val userBean = UserBean()
                userBean.birthday = it.getValue<UserEntity>()!!.birthday
                userBean.username = it.getValue<UserEntity>()!!.username
                userBean.pwd = it.getValue<UserEntity>()!!.pwd
                ShopApplication.daoSession.userBeanDao.insert(userBean);
//                GreenDaoManager.save(userBean)
//                val newDevSession = DaoMaster.newDevSession(this, "")
//                newDevSession.userBeanDao.queryBuilder().where(UserBeanDao.Properties.Username.eq("")).list().get(0)
            }else{
                toast("注册失败")
            }
        })
    }

    override fun getAuth(): String {
        return et_act_register_auth.text.toString()
    }

    override fun successAuth(auth: Deferred<Int>) {
        doUiThread(auth,{
            this.auth = it
            val build = Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("验证码")
                .setContentText("${it}")
                .build()
            val systemService = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            systemService.notify(1,build)
        })
    }
}
